package edu.gmu.project.swe;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Arrays;
import java.util.HashMap;

public class SocketClientHandler implements Runnable {

	private String[] files;
	private String[] response;
	private HashMap<String, String> fileMap = new HashMap<String, String>();
	private HashMap<String, String> serverMap = new HashMap<String, String>();
	private Socket soc;
	private static BufferedInputStream bis;
	private static FileInputStream fis;
	private static BufferedOutputStream bout;
	private static InputStream instr;
	private static FileOutputStream outstr;
	private String path = "ServerHome/";
	private String text = "";
	private File f = new File(path);
	File[] listOfFiles = f.listFiles();

	public SocketClientHandler(Socket soc) {
		this.soc = soc;
	}

	@Override
	public void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					soc.getInputStream()));
			PrintWriter out = new PrintWriter(soc.getOutputStream(), true);
			System.out.println("Thread started with name:"
					+ Thread.currentThread().getName());
			String inputLine, outputLine = null;
			bis = new BufferedInputStream(fis);
			bout = new BufferedOutputStream(soc.getOutputStream());

			// Initiate conversation with client
			// KnockKnockProtocol kkp = new KnockKnockProtocol();
			// outputLine = kkp.processInput(null);
			out.println(outputLine);

			while ((inputLine = in.readLine()) != null) {
				System.out.println("\nThis is what I got from client " +inputLine);
				if (inputLine.contains("1")) {
					// System.out.print("After" +inputLine);
					/*
					 * response = inputLine.split(":"); files =
					 * response[1].split(","); for (int i = 0; i < files.length;
					 * i++) { String file = files[i]; System.out.println(file);
					 * int ptr = i + 2; fileMap.put(file, response[ptr]); }
					 * System.out.println(fileMap); break;
					 */
					// String path = "/ServerHome/Files/";
					// String userdir = path + in.readLine();
					// System.out.print (userdir);
					 String msg = "3-";
					for (int j = 0; j < listOfFiles.length; j++) {
						if (listOfFiles[j].isFile()) {
							text = listOfFiles[j].getName();
							long length = listOfFiles[j].length();
							// System.out.print(length);
							
							byte[] bytes = new byte[1024];

							// filename, length. get the total offset of the
							// text file.
							long totalOffset;
							totalOffset = (length / 1024);
							// System.out.print(totalOffset);

							//out.println(text);
							//System.out.print(MsgCode.FILE_SUMMARY.getValue() + "-"+ text + ':' + totalOffset + ",");
							msg += text + ':' + totalOffset + ",";
							serverMap.put(text, String.valueOf(totalOffset));
						}
					}
					msg = msg.substring(0, msg.length()-1);
					System.out.print("Message to send to client" +msg);
					out.println(msg);
					// outputLine = "2:test.rtf:307";
					// out.println(outputLine);

				}
				if (inputLine.contains("3")) {
					
					
					// After receiving the list of files and the offset pointer
					// from the user
					// I need to get that file and skip the number of offset
					// pointer and then
					// start sending file from that offset.
					
					String [] splitin1 = inputLine.split("-");
					System.out.print("\nFirst split" +Arrays.toString(splitin1));
					String [] splitin2 = splitin1[1].split(",");
					System.out.print("\nSecond split" +Arrays.toString(splitin2));
					String [] splitin3 ;
					for(int i= 0; i< splitin2.length; i++ ){
						splitin3 = splitin2[i].split(":");
						fileMap.put(splitin3[0], splitin3[1]);
						System.out.print("\nThird split" +Arrays.toString(splitin3));
					}
					
					System.out.print("\nThis is the list received from client" +fileMap);
					//check if the files exists in the directory
					for(String clientFile : fileMap.keySet()){
						boolean Match = serverMap.containsKey(clientFile);
						if(Match){
							String msg = ("0-"+clientFile);
							out.print(msg);
							System.out.print("Message to be sent to client" +msg);
							long serverOffset = Long.parseLong(serverMap.get(clientFile));
							long clientOffset = Long.parseLong(fileMap.get(clientFile));
							
							byte[] bytes = new byte[1024];
							int count;
							long pointer= (serverOffset - clientOffset);
							int offset = 0;
							while ((count = bis.read(bytes)) > 0) {
								if (offset >= pointer)
									bout.write(bytes, 0, count);
								offset++;
		
							}
						}
						else if(!Match){
							String msg = ("-1"+clientFile);
						}
					
					bout.flush();
					fis.close();
					
					}

				} else if (inputLine.contains("4")) {
					break;
				}
				//
				// if (outputLine.contains("3"))
				// break;
			}

			soc.close();
			out.close();
			in.close();

		} catch (IOException e) {
			System.out
					.println("Exception caught when trying to listen on port "
							+ 4444 + " or listening for a connection");
			System.out.println(e.getMessage());
		}

	}

}
